import { defineStore } from 'pinia'
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  }),
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        console.log('Store开始调用登录API，参数：', username, password)
        login(username, password)
          .then(res => {
            console.log('登录API响应：', res)
            
            // 新的登录逻辑，不依赖token
            if (res.code === 200 && res.data && res.data.userInfo) {
              const userInfo = res.data.userInfo
              const token = res.data.token
              
              // 存储用户信息到本地存储
              localStorage.setItem('username', username)
              localStorage.setItem('name', userInfo.name || username)
              localStorage.setItem('avatar', userInfo.avatar || '')
              localStorage.setItem('roles', JSON.stringify([userInfo.role || 'user']))
              
              // 更新状态
              this.name = userInfo.name || username
              this.avatar = userInfo.avatar || ''
              this.roles = [userInfo.role || 'user']
              
              // 创建标识，表示用户已登录
              // console.log('后端返回的token：', token)
              setToken(token) // 后端返回的token
              
              resolve(res)
            } else {
              reject(new Error(res.message || '登录失败'))
            }
          })
          .catch(error => {
            console.error('登录API异常：', error)
            reject(error)
          })
      })
    },

    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        // 从本地存储获取用户信息
        const username = localStorage.getItem('username')
        const name = localStorage.getItem('name')
        const avatar = localStorage.getItem('avatar')
        const roles = JSON.parse(localStorage.getItem('roles') || '[]')
        
        if (username && name) {
          this.name = name
          this.avatar = avatar
          this.roles = roles
          resolve({ name, avatar, roles })
        } else {
          // 如果本地没有用户信息，清除登录状态
          this.resetState()
          reject(new Error('获取用户信息失败，请重新登录'))
        }
      })
    },

    // 退出登录
    logout() {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          this.resetState()
          resolve()
        }).catch(error => {
          console.error('登出API异常：', error)
          this.resetState()
          resolve()
        })
      })
    },

    // 重置状态
    resetState() {
      this.token = ''
      this.name = ''
      this.avatar = ''
      this.roles = []
      this.permissions = []
      removeToken()
      localStorage.removeItem('username')
      localStorage.removeItem('name')
      localStorage.removeItem('avatar')
      localStorage.removeItem('roles')
    }
  }
}) 